//
//  HLBaseTableCtl.m
//  s.
//
//  Created by fanshijian on 2022/8/25.
//  Copyright © 2022 J. All rights reserved.
//

#import "BaseTableControl.h"
#import <CALayer+YYAdd.h>
#import <LYEmptyView/LYEmptyViewHeader.h>
@interface BaseTableControl ()

@property (weak, nonatomic) UITableView *tableView;
@property (assign, nonatomic) BOOL dloaded;
@property (assign, nonatomic,getter=isRefreshing) BOOL refreshing;

@end

@implementation BaseTableControl

- (UITableViewStyle)style {
    return UITableViewStylePlain;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _tableInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.view.backgroundColor = KLColor(self.containerColor);
    KLWKSelf
    self.emptyViewBlock = ^(MASConstraintMaker * _Nonnull make) {
        KLSTSelf
        kMakeEdgeV(self.tableInsets);
    };
}

- (void)setTableInsets:(UIEdgeInsets)tableInsets {
    _tableInsets = tableInsets;
    KLWKSelf
    self.emptyViewBlock = ^(MASConstraintMaker * _Nonnull make) {
        KLSTSelf
        kMakeEdgeV(self.tableInsets);
    };
}

- (void)setShowNoContent:(BOOL)showNoContent{
//    [super setShowNoContent:showNoContent];
    if (self.showNoContent) {
        if (_tableView.mj_footer) {_tableView.mj_footer = nil;}
    }else{
        if (_dataSources.count > 0 && self.can_pullup && !_tableView.mj_footer){
            self.tableView.mj_footer = [self.mj_footer_class footerWithRefreshingTarget:self refreshingAction:@selector(_more)];
            if ([self.tableView.mj_footer isKindOfClass:MJRefreshBackNormalFooter.class]) {
                MJRefreshBackNormalFooter *header = (MJRefreshBackNormalFooter *)self.tableView.mj_footer;
                header.stateLabel.textColor = KLColor(@"#999999");
                header.stateLabel.font = U_font(14);
            }
        }
    }
}

- (BOOL)jy_haveData {
    return self.dataSources.count!=0;
}
- (NSString *)containerColor{return @"#f5f5f5";}

- (Class)mj_footer_class{
    return MJRefreshBackNormalFooter.class;
}
- (Class)mj_header_class {
    return MJRefreshNormalHeader.class;
}

- (BOOL)sectionHeadersPinToVisibleBounds{return NO;}
- (BOOL)can_pulldown{
    return YES;
}
- (BOOL)can_pullup{
    return NO;
}

- (UITableView *)tableV{
    return self.tableView;
}

#pragma mark - 懒加载
- (UITableView *)tableView {
    if ( !_tableView ) {
        UITableView *obj = [[UITableView alloc] initWithFrame:self.view.bounds style:self.style];
        obj.backgroundColor = UIColor.whiteColor;
        [self.view addSubview:_tableView = obj];
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            if (self.tableLayoutBlock) {
                self.tableLayoutBlock(make);
                self.tableLayoutBlock = nil;
            }else{
                kMakeEdgeV(self.tableInsets);
            }
        }];
        if (self.can_pulldown) {
            obj.mj_header = [self.mj_header_class headerWithRefreshingTarget:self refreshingAction:@selector(_refresh)];
            obj.mj_header.backgroundColor = KLColor(self.containerColor);
            obj.mj_header.isCollectionViewAnimationBug = YES;
            if ([obj.mj_header isKindOfClass:[MJRefreshNormalHeader class]]) {
                MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)obj.mj_header;
                header.stateLabel.textColor = KLColor(@"#999999");
                header.stateLabel.font = U_font(14);
                header.lastUpdatedTimeLabel.textColor = KLColor(@"#999999");
                header.lastUpdatedTimeLabel.font = U_font(14);
            }
        }
        obj.backgroundColor                        = KLColor(self.containerColor);
        if (@available(iOS 11.0, *)) {
            obj.contentInsetAdjustmentBehavior     = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            obj.sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }
        
        obj.tableViewAdapter.headerHeight = 0.001;
        obj.tableViewAdapter.footerHeight = 0.001;
        LYEmptyView * emptyView = [LYEmptyView emptyViewWithImage:U_imageNamed(self.empty_image) titleStr:@"暂无数据" detailStr:nil];
        emptyView.contentViewY = 100;
        _tableView.ly_emptyView = emptyView;
    }
    return _tableView;
}

- (void)_refresh{
    _refreshing = YES;
    [self refreshRequest];
}
/** 加载更多  */
- (void)_more{
    [self loadMore];
}

/** 刷新  */
- (void)setDataSources:(NSArray<MainSectionModel *> *)dataSources {
    if (_dataSources != dataSources) {
        if (!_dataSources && dataSources.count == 0) {
            self.showNoContent = YES;
        }else{
            if (!_dataSources) {[self.view.layer addFadeAnimationWithDuration:0.25 curve:(UIViewAnimationCurveEaseIn)];}
            _dataSources = dataSources;
            self.showNoContent = (dataSources.count == 0);
            _dloaded     = YES;
            [self reloadIfNeeded];
        }
    }else if (!_dataSources && !dataSources){//初始数据为空
        self.showNoContent = (_dataSources.count == 0);
    }
}

- (void)_handleMore:(NSArray *)dataSources section:(MainSectionModel *)ms {
    BOOL reduce = NO;
    if (_dataSources.count > 0) {
        if ((!dataSources || dataSources.count == 0) && !ms.modified) {//没有更多数据
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        if (ms) {//部分section刷新, 如果ms依然有，直接刷新
            if(dataSources.count) [ms.items addObjectsFromArray:dataSources];
        }else{
            NSMutableArray *ds = (id)_dataSources;
            if (![ds isKindOfClass:NSMutableArray.class] ) ds = [NSMutableArray arrayWithArray:_dataSources];
            if (ds.count > 100) {//>50 item remove 10 items from top
                [ds removeObjectsInRange:NSMakeRange(0, 10)];
                reduce = YES;
            }
            [ds addObjectsFromArray:dataSources];
            _dataSources = ds;
        }
    }else{
        if (!dataSources || dataSources.count == 0) {//没有更多数据
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }else{
            _dataSources = dataSources.mutableCopy;
        }
    }
    if (ms && ms.idx) {
        [self _reloadSections:[NSIndexSet indexSetWithIndex:ms.idx.integerValue] reduced:reduce];
    }else{
        [self _reloadIfNeededReduced:reduce];
    }
}

- (void)reloadIfNeeded {
    [self _reloadIfNeededReduced:NO];
}

- (void)_resetFooterState{
    if (self.can_pullup && self.can_reset_footer && self.tableView.mj_footer.state == MJRefreshStateNoMoreData) {
        [self.tableView.mj_footer resetNoMoreData]; //恢复数据
    }
}

- (BOOL)can_reset_footer{
    return _dataSources.count == 0 || _dloaded;
}

- (void)_reloadIfNeededReduced:(BOOL)reduce{
    [self _resetFooterState];
    if (reduce) [self _reduceScrollTableView];
    [UIView performWithoutAnimation:^{
        self.tableView.tableViewAdapter.keyPathOfSubData = @"items";
        self.tableView.cellDatas = self.dataSources;
        self.tableView.headerDatas = self.dataSources;
        self.tableView.footerDatas = self.dataSources;
        [self.tableView reloadData];
    }];
}

- (void)_reloadSections:(NSIndexSet *)indexSet reduced:(BOOL)reduce{
    [self _resetFooterState];
    if (reduce) [self _reduceScrollTableView];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
}

- (void)_reduceScrollTableView{
    if (self.dataSources.count - 10 > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.dataSources.count - 10] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

- (void)_endRefresh{
    if (_tableView.mj_header.isRefreshing) {
        [_tableView.mj_header endRefreshing];
    }
    if (_tableView.mj_footer.isRefreshing) {
        [_tableView.mj_footer endRefreshing];
    }
    _refreshing = NO;
}

#pragma mark - 请求返回
- (void)finishRequestWithOperation:(AFHTTPRequestOperation *)operation data:(id)data vmsg:(NSString *)msg more:(BOOL)more {
    [super finishRequestWithOperation:operation data:data vmsg:msg more:more];
    BOOL isRefresh = self.isRefreshing;
    [self _endRefresh];
    if (!msg) {
        id dat = data[@"data"];
        if ([dat respondsToSelector:@selector(count)] && [dat count] > 0) {
            [self transformMetaData:dat handle:(more && !isRefresh) ? ^(id _Nonnull list, MainSectionModel *ms) {
                [self _handleMore:list section:ms];
            } : NULL];
        }else{
            if (more) {
                if ([self can_pullup]) [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                self.dataSources = nil;
            }
        }
    }
}

- (void)transformMetaData:(NSDictionary *)data handle:(void (^)(id, MainSectionModel *))handle{}

@end
